<template>
    <div style="margin: 0;padding: 0;">
        <div class="header">
            <el-breadcrumb separator-class="el-icon-arrow-right" style="display: inline-block;margin-left: 10px;">
                <el-breadcrumb-item :to="{ path: '/home/message' }">消息中心</el-breadcrumb-item>
                <el-breadcrumb-item>{{ activeName }}</el-breadcrumb-item>
            </el-breadcrumb>
            <UserAcatar @transfer="change" />
        </div>
        <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick" style="max-width: 100%;margin: 5px auto;">
            <el-tab-pane name="通知" v-loading="listLoading">
                <span slot="label">通 知</span>
                <div class="content" v-if="(infoList ? infoList : []).length == 0"
                    style="display: flex;align-items: center;justify-content: center;height: 400px;color: #ccc;">
                    然而没有任何通知
                </div>
                <div class="content" v-else>
                    <el-card v-for="(item, i) in infoList" :key="item.create_time + '' + i">
                        <el-popover placement="top" width="300" trigger="hover">
                            <div style="display: flex;justify-content: space-between;">
                                <!-- 头像 -->
                                <div
                                    style="width: 80px;height: 80px;overflow: hidden;display: flex;align-items: center;justify-content: center;border-radius: 5px;">
                                    <div class="avatarn" v-if="!item.avatar"
                                        style="background-color: #ccc;display: flex;justify-content: center;align-items: center;">
                                        <i class="el-icon-picture-outline"></i>
                                    </div>
                                    <el-image v-else style="height: 80px;" :src="item.avatar" />
                                </div>
                                <div style="width: 200px;margin-top: 20px;" v-if="item.user_auth == 'admin_per'">
                                    <h4>{{ item.user_name }}</h4>
                                </div>
                                <div style="width: 200px;" v-else>
                                    <h4>{{ item.user_name }}</h4>
                                    <p>{{ item.signature }}</p>
                                </div>
                            </div>
                            <span slot="reference" style="font-weight: bold;" class="sender">
                                @{{ item.user_name }}
                            </span>
                        </el-popover>

                        <p style="margin-top: 10px;" v-if="hasHtmlTags(item.content)" v-html="item.content">
                        </p>
                        <p style="margin-top: 10px;" v-else>{{ item.content }}</p>
                        <p style="font-size: smaller;color: #ccc;margin-top: 10px;">{{ item.update_time }}</p>
                    </el-card>
                </div>
            </el-tab-pane>
            <el-tab-pane label="收到的评论" name="收到的评论" v-loading="listLoading">
                <div class="content" v-if="(messageList ? messageList : []).length == 0"
                    style="display: flex;align-items: center;justify-content: center;height: 400px;color: #ccc;">
                    然而没有任何回复
                </div>
                <div class="content" v-else>
                    <el-collapse v-model="actName" accordion>
                        <el-collapse-item :title="course.assignment_title" :name="i + ''" v-for="(course, i) in messageList"
                            :key="course.assignment_id">

                            <el-card v-for="(item) in course.infoList" :key="item.sender">
                                <el-popover placement="top" width="300" trigger="hover">
                                    <div style="display: flex;justify-content: space-between;">
                                        <!-- 头像 -->
                                        <div
                                            style="width: 80px;height: 80px;overflow: hidden;display: flex;align-items: center;justify-content: center;border-radius: 5px;">
                                            <div class="avatarn" v-if="!item.avatar"
                                                style="background-color: #ccc;display: flex;justify-content: center;align-items: center;">
                                                <i class="el-icon-picture-outline"></i>
                                            </div>
                                            <el-image v-else style="height: 80px;" :src="item.avatar" />
                                        </div>
                                        <div style="width: 200px;">
                                            <h4>{{ item.user_name }}</h4>
                                            <p>{{ item.signature }}</p>
                                        </div>
                                    </div>

                                    <div slot="reference"
                                        style="width: 80px;height: 80px;overflow: hidden;display: flex;align-items: center;justify-content: center;border-radius: 5px;">
                                        <div class="avatarn" v-if="!item.avatar"
                                            style="background-color: #ccc;display: flex;justify-content: center;align-items: center;">
                                            <i class="el-icon-picture-outline"></i>
                                        </div>
                                        <el-image v-else style="height: 80px;" :src="item.avatar" />
                                    </div>
                                </el-popover>

                                <el-timeline style="margin-top: 20px;">
                                    <el-timeline-item v-for="(o, i) in course.messagesByPerson[item.sender]"
                                        :key="o.message_id" :timestamp="o.create_time" placement="top">
                                        <p style="line-height: 2;" v-if="userInfo.user_id != o.sender">
                                            <span class="sender">
                                                @{{ o.user_name }}
                                            </span>
                                        </p>
                                        <p style="line-height: 2;" v-if="hasHtmlTags(o.content)" v-html="o.content">
                                        </p>
                                        <p style="line-height: 2;" v-else>
                                            {{ o.content }}
                                        </p>

                                        <p style="line-height: 2;">
                                            {{ o.update_time }}
                                            <span style="cursor: pointer;margin-left: 10px;" class="reply" @click="reply(o)"
                                                v-if="userInfo.user_id != o.sender">
                                                <i class="el-icon-chat-round"></i> 回复
                                            </span>
                                            <span style="cursor: pointer;margin-left: 10px;" @click="upvote(item.s, o)"
                                                v-if="userInfo.user_id != o.sender">
                                                <span class="favour" v-if="o.isliked" style="color:#65cce9;">
                                                    <i class="iconfont icon-dianzan"></i>
                                                </span>
                                                <span class="favour" v-else>
                                                    <i class="iconfont icon-dianzan"></i>
                                                </span>
                                                {{ o.num }}
                                            </span>
                                        </p>
                                        <div style="margin-top: 10px;" v-if="o.isreply">
                                            <Tinymce ref="editor" v-model="replyval" :height="40" :menubar="''"
                                                @critic="Critic" />
                                        </div>
                                    </el-timeline-item>
                                </el-timeline>
                            </el-card>
                        </el-collapse-item>
                    </el-collapse>
                </div>
            </el-tab-pane>
            <el-tab-pane label="收到的赞" name="收到的赞" v-loading="listLoading">
                <div class="content" v-if="(fList ? fList : []).length == 0"
                    style="display: flex;align-items: center;justify-content: center;height: 400px;color: #ccc;">
                    你还没有被赞过，不要气馁吆~
                </div>
                <div class="content" v-else>
                    <el-card v-for="(item, i) in fList" :key="item.create_time + '' + i">
                        <div style="display: flex;align-items: center;justify-content: space-between;">
                            <div style="display: flex;align-items: center;">
                                <!-- 头像 -->
                                <div
                                    style="width: 80px;height: 80px;overflow: hidden;display: flex;align-items: center;justify-content: center;border-radius: 5px;">
                                    <div class="avatarn" v-if="!item.avatar"
                                        style="background-color: #ccc;display: flex;justify-content: center;align-items: center;">
                                        <i class="el-icon-picture-outline"></i>
                                    </div>
                                    <el-image v-else style="height: 80px;" :src="item.avatar" />
                                </div>
                                <div
                                    style="height: 80px;display: flex;flex-direction: column;justify-content: space-around;margin-left: 20px;">
                                    <p>
                                        <span style="font-weight: bold;">
                                            {{ item.user_name }}
                                        </span>
                                        <span>
                                            赞了你的评论
                                        </span>
                                    </p>
                                    <p style="font-size: smaller;">{{ item.create_time }}</p>
                                </div>
                            </div>
                            <div v-if="hasHtmlTags(item.content)">
                                <p v-html="item.content"></p>
                            </div>
                            <div v-else>
                                <p>{{ item.content }}</p>
                            </div>
                        </div>
                    </el-card>
                </div>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>

<script>
import UserAcatar from "@/components/UserAcatar.vue";
import '@/assets/icon/iconfont.css'
import Tinymce from "@/components/Tinymce";
export default {
    name: 'Message',
    components: {
        UserAcatar,
        Tinymce
    },
    data() {
        return {
            userInfo: {},
            keyword: "",
            replyval: '',
            fList: null,
            infoList: null,
            activeName: '通知',
            listLoading: true,
            messagesByPerson: null,
            messageList: null,
            actName: '0'
        }
    },
    methods: {
        // 将标准时间转换为YYYY-MM-DD HH:MM:SS类型的
        formTime(time) {
            let newtime = new Date(time);
            // console.log(new Date(time), "要进行转换的时间");
            const year = newtime.getFullYear();
            const month = String(newtime.getMonth() + 1).padStart(2, "0");
            const day = String(newtime.getDate()).padStart(2, "0");
            const hours = String(newtime.getHours()).padStart(2, "0");
            const minutes = String(newtime.getMinutes()).padStart(2, "0");
            const seconds = String(newtime.getSeconds()).padStart(2, "0");

            const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            return formattedDate;
        },
        // 将头像组件中的路由再传递给homeview
        change(msg) {
            this.$emit("transfer", msg);
        },
        // 判断是否含有html标签
        hasHtmlTags(str) {
            const pattern = /<\/?\w+[^>]*>/g;
            return pattern.test(str);
        },
        groupByProperty(arr, prop) {
            return Object.values(
                arr.reduce((groups, item) => {
                    const value = item[prop];
                    groups[value] = groups[value] || [];
                    groups[value].push(item);
                    return groups;
                }, {})
            );
        },
        // 获取数据库数据
        async getMessage() {
            let res = await this.$axios.post('/message/getmessage', { user_id: this.userInfo.user_id })
            console.log(res);
            if (res.code == 200) {
                this.listLoading = false
                const List = res.data.map(item => {
                    return { ...item, create_time: this.formTime(item.create_time), update_time: this.formTime(item.update_time), avatar: item.avatar ? `http://localhost:3000/image/getavatar/${encodeURIComponent(item.avatar)}` : item.avatar }
                })
                console.log(this.groupByProperty(List, 'assignment_id'));
                this.messageList = this.groupByProperty(List, 'assignment_id').map(coursemsg => {

                    const senders = coursemsg.filter(item => item.sender != this.userInfo.user_id)
                    const mineL = coursemsg.filter(item => item.sender == this.userInfo.user_id)
                    console.log(mineL);

                    const messagesByPerson = senders.reduce(function (result, message) {
                        if (!result[message.sender]) {
                            result[message.sender] = [];
                        }
                        result[message.sender].push(message);
                        return result;
                    }, {});
                    console.log(messagesByPerson);

                    let infoList = Object.keys(messagesByPerson).map(item => {
                        return { sender: item, avatar: senders.filter(r => r.sender == item)[0].avatar, user_name: senders.filter(r => r.sender == item)[0].user_name, signature: senders.filter(r => r.sender == item)[0].signature }
                    })
                    console.log(infoList);

                    Object.keys(messagesByPerson).forEach(item => {
                        messagesByPerson[item] = [
                            ...messagesByPerson[item].map(r => {
                                return { ...r, isreply: false }
                            }),
                            ...mineL.filter(s => s.recipient == item)
                        ].sort(function (a, b) {
                            return new Date(a.create_time) - new Date(b.create_time);
                        })
                    })
                    console.log(messagesByPerson);
                    // this.messagesByPerson = messagesByPerson

                    return { assignment_id: coursemsg[0].assignment_id, assignment_title: coursemsg[0].assignment_title, infoList: infoList, messagesByPerson: messagesByPerson }
                }).filter(assign => assign.infoList.length != 0)
                console.log(this.messageList);
            }
        },
        // 获取点赞信息
        async getfavour() {
            let res = await this.$axios.post('/message/getfavour', { user_id: this.userInfo.user_id })
            console.log(res);
            if (res.code == 200) {
                this.fList = res.data.map(item => {
                    return { ...item, create_time: this.formTime(item.create_time), avatar: item.avatar ? `http://localhost:3000/image/getavatar/${encodeURIComponent(item.avatar)}` : item.avatar }
                })
                this.listLoading = false
            }
        },
        // 获取通知
        async getInfo() {
            let res = await this.$axios.post('/message/getinfo', { user_id: this.userInfo.user_id })
            console.log(res);
            if (res.code == 200) {
                this.infoList = res.data.map(item => {
                    return { ...item, create_time: this.formTime(item.create_time), update_time: this.formTime(item.update_time), avatar: item.avatar ? `http://localhost:3000/image/getavatar/${encodeURIComponent(item.avatar)}` : item.avatar }
                })
                this.listLoading = false
            }
        },
        // 回复
        async reply(r) {
            // console.log(r);
            // if (!this.replyval) {
            //     this.$message.info('请输入内容')
            // } else {
            //     let obj = { sender: this.userInfo.user_id, recipient: r.sender, content: this.replyval, type: '#', r_msg_id: r.message_id }
            //     let res = await this.$axios.post('/message/reply', obj)
            //     console.log(res);
            //     if (res.code == 200) {
            //         this.replyval = ''
            //         r.isreply = false
            //     }
            // }
            console.log(r);
            r.isreply = !r.isreply
            this.r = r
        },
        // 回复
        async Critic(msg) {
            console.log(msg);
            if (msg) {
                console.log(this.replyval);
                if (this.replyval != "") {
                    let obj = { sender: this.userInfo.user_id, recipient: this.r.sender, content: this.replyval, type: '#', r_msg_id: this.r.message_id, assignment_id: this.r.assignment_id }
                    let res = await this.$axios.post('/message/reply', obj)
                    console.log(res);
                    if (res.code == 200) {
                        this.replyval = ''
                        this.r.isreply = false
                        await this.getMessage()
                    }
                }
            }
        },
        // 点赞
        async upvote(s, r) {
            // console.log(s);
            // console.log(r);
            let obj = { user_id: r.sender, message_id: r.message_id, up_user_id: this.userInfo.user_id }
            let res = await this.$axios.post('/message/upvote', obj)
            // console.log(res);
            if (res.code == 200) {
                r.num += 1
                r.isliked = true
            }
            if (res.code == 201) {
                r.num -= 1
                r.isliked = false
            }
        },
        // 切换
        async handleClick(tab, event) {
            console.log(tab.name, event);
            if (tab.name == '通知') {
                this.listLoading = true
                await this.getInfo()
            }
            if (tab.name == '收到的评论') {
                this.listLoading = true
                await this.getMessage()
            }
            if (tab.name == '收到的赞') {
                this.listLoading = true
                await this.getfavour()
            }
        },

    },
    async mounted() {
        console.log(JSON.parse(JSON.stringify(this.$store.state.user_info)));
        this.userInfo = {
            ...JSON.parse(JSON.stringify(this.$store.state.user_info))
        };
        await this.getInfo()
    }
}
</script>
  
  <!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.header {
    width: 100%;
    height: 80px;
    border-bottom: 2px solid #bbb;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    /* justify-content: flex-end; */
}

.sender {
    font-weight: bold;
    cursor: pointer;
}

.sender:hover,
.reply:hover,
.favour:hover {
    color: #65cce9;
}

.avatarn {
    width: 80px;
    height: 80px;
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>
  